package com.ruoyi.pv.service.impl;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

import com.doudou.core.container.ListUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.doudou.core.lang.ObjUtil;
import com.doudou.core.str.StrUtil;
import com.ruoyi.cert.domain.Cert;
import com.ruoyi.cert.service.ICertService;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.ex.domain.ExStudyReload;
import com.ruoyi.pv.domain.PvClassScore;
import com.ruoyi.pv.domain.PvTrainingClass;
import com.ruoyi.pv.domain.PvUserInfo;
import com.ruoyi.pv.service.IPvClassScoreService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.pv.mapper.PvStudentRecordMapper;
import com.ruoyi.pv.domain.PvStudentRecord;
import com.ruoyi.pv.service.IPvStudentRecordService;

/**
 * 学员报名记录Service业务层处理
 *
 * @author zzx
 * @date 2023-04-20
 */
@Service
@Slf4j
public class PvStudentRecordServiceImpl implements IPvStudentRecordService {
    @Autowired private PvStudentRecordMapper pvStudentRecordMapper;
    @Autowired private ICertService certService;
    @Autowired private IPvClassScoreService classScoreService;

    private static final ExecutorService POOL = new ThreadPoolExecutor(1, 1,
            0L, TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<>());
    private static Future<Integer> FUTURE = null;

    @Override
    public boolean isFuture(){
        return FUTURE == null || FUTURE.isDone();
    }


    /**
     * 查询学员报名记录
     *
     * @param id 学员报名记录主键
     * @return 学员报名记录
     */
    @Override
    public PvStudentRecord selectPvStudentRecordById(Long id) {
        return pvStudentRecordMapper.selectPvStudentRecordById(id);
    }

    /**
     * 查询学员报名记录列表
     *
     * @param pvStudentRecord 学员报名记录
     * @return 学员报名记录
     */
    @Override
    public List<PvStudentRecord> selectPvStudentRecordList(PvStudentRecord pvStudentRecord) {
        return pvStudentRecordMapper.selectPvStudentRecordList(pvStudentRecord);
    }

    /**
     * 新增学员报名记录
     *
     * @param pvStudentRecord 学员报名记录
     * @return 结果
     */
    @Override
    public int insertPvStudentRecord(PvStudentRecord pvStudentRecord) {
        pvStudentRecord.setCreateTime(DateUtils.getNowDate());
        return pvStudentRecordMapper.insertPvStudentRecord(pvStudentRecord);
    }

    /**
     * 修改学员报名记录
     *
     * @param pvStudentRecord 学员报名记录
     * @return 结果
     */
    @Override
    public int updatePvStudentRecord(PvStudentRecord pvStudentRecord) {
        //计算总分
        try{
            pvStudentRecord.setScoreTotal(ListUtil.sumInt(pvStudentRecord.getChildrenScoreList()) + ListUtil.sumInt(pvStudentRecord.getPuerperaScoreList()));
        }catch (Exception e){
            log.error("",e);
            pvStudentRecord.setScoreTotal(0);
        }
        int i = pvStudentRecordMapper.updatePvStudentRecord(pvStudentRecord);
        updateQualified(pvStudentRecord.getId());
        return i;
    }

    /**
     * 批量删除学员报名记录
     *
     * @param ids 需要删除的学员报名记录主键
     * @return 结果
     */
    @Override
    public int deletePvStudentRecordByIds(Long[] ids) {
        return pvStudentRecordMapper.deletePvStudentRecordByIds(ids);
    }

    /**
     * 删除学员报名记录信息
     *
     * @param id 学员报名记录主键
     * @return 结果
     */
    @Override
    public int deletePvStudentRecordById(Long id) {
        return pvStudentRecordMapper.deletePvStudentRecordById(id);
    }

    @Override
    public List<PvStudentRecord> selectPvTrainingClassStudentList(Long classId, SysUser user) {
        //处理排序 评分表的排序优先级大于成绩
        Map<String, Object> params = user.getParams();
        Object tableScoreOrder = params.get("tableScoreOrder");
        if (ObjUtil.isNotNull(tableScoreOrder) && StrUtil.isNotBlank(tableScoreOrder.toString())){
            params.remove("scoreOrder");
        }
        user.setParams(params);
        return pvStudentRecordMapper.selectPvTrainingClassStudentList(classId, user);
    }

    @Override
    public int completeCourses(Long classId,Long[] ids) {
        return pvStudentRecordMapper.completeCourses(classId,ids);
    }

    /**
     * # 2024-01-03 修改为查询最近一次的报名记录
     * 判断用户今年是否有报名记录
     * @param userId
     * @return
     */
    @Override
    public PvStudentRecord thisYearHas(long userId) {
        PvStudentRecord pvStudentRecord = PvStudentRecord.builder().stuId(userId).build();
        List<PvStudentRecord> pvStudentRecords = pvStudentRecordMapper.selectPvStudentRecordList(pvStudentRecord);
        if (ListUtil.isEmpty(pvStudentRecords)){
            return null;
        }
        return pvStudentRecords.get(pvStudentRecords.size()-1);
    }



    /**
     * 执行颁证任务
     */
    @Override
    public void submitCert(Cert cert){
        if (isFuture()){
            DateTime date = DateUtil.date();
            cert.setCreateBy(SecurityUtils.getUsername());
            cert.setDeptId(SecurityUtils.getDeptId());
            cert.setIssuanceDate(date);//发证时间
            //cert.setExp(DateUtil.endOfYear(DateUtil.date().offset(DateField.YEAR,1)));//过期时间，明年的最后一天
            cert.setApprovalDate(date);
            cert.setApprovalBy(SecurityUtils.getUsername());
            cert.setApprovalInfo("结业");
            FUTURE = POOL.submit(()-> certService.insertCert(cert));
        }else{
            throw new ServiceException("颁证任务尚未结束，请稍后再试");
        }
    }

    @Override
    public int updatePvStudentRecordCertByStudent(Long studentId, Long certId) {
        return pvStudentRecordMapper.updatePvStudentRecordCertByStudent(studentId,certId);
    }

    private static final String children = "children" , puerpera = "puerpera";

    /**
     * 创建评分表
     * @return {}
     */
    @Override
    public List<Integer> createScore(boolean isChildren){
        return isChildren ? createScore(children) : createScore(puerpera);
    }

    @Override
    public PvStudentRecord selectPvStudentRecordThisYear(Long userId) {
        return pvStudentRecordMapper.selectPvStudentRecordThisYear(userId);
    }

    @Override
    public List<JSONObject> getNotInClassStudentList(Long classId, Long deptId) {
        return pvStudentRecordMapper.getNotInClassStudentList(classId,deptId);
    }

    @Override
    public int insertPvStudentRecordAll(List<PvStudentRecord> beanList) {
        return pvStudentRecordMapper.insertPvStudentRecordAll(beanList);
    }

    /**
     * 修改用户合格状态
     * @param id
     */
    @Override
    public void updateQualified(Long id) {
        try{
            PvStudentRecord record = pvStudentRecordMapper.selectPvStudentRecordById(id);
            PvUserInfo userInfo = record.getStudent().getUserInfo(PvUserInfo.class);
            String InitialRefresher = userInfo.getReservedOne();//初复训
            PvTrainingClass clazz = record.getTrainingClass();
            PvClassScore classScore = classScoreService.selectPvClassScoreById(clazz.getId());
            //先判断考试分数
            String isQualified = "0";
            ExStudyReload exStudyReload = record.getExStudyReload();
            if (ObjectUtil.isNotEmpty(exStudyReload) && ObjectUtil.isNotEmpty(exStudyReload.getScore())){
                int compareExScore = "0".equals(InitialRefresher) ? classScore.getFirstExScore() : classScore.getReExScore();
                if (exStudyReload.getScore() != 0 && exStudyReload.getScore() >= compareExScore){
                    isQualified = "1";//考试分数合格
                }
            }
            //如果考试分数合格，判断评分表分数
            if ("1".equals(isQualified)){
                int compareTableScore = "0".equals(InitialRefresher) ? classScore.getFirstTableScore() : classScore.getReTableScore();
                if (record.getScoreTotal() < compareTableScore){
                    isQualified = "0";
                }
            }
            //修改
            pvStudentRecordMapper.updatePvStudentRecord(PvStudentRecord.builder().id(id).reservedOne(isQualified).build());
        }catch (Exception e){
            log.error("更新用户合格状态失败",e);
        }
    }

    @Override
    public PvStudentRecord selectPvStudentRecordByClassIdAndUserId(Long classId, Long userId) {
        return pvStudentRecordMapper.selectPvStudentRecordByClassIdAndUserId(classId,userId);
    }

    @Override
    public List<PvStudentRecord> selectPvStudentRecordListByStuId(Long userId) {
        return pvStudentRecordMapper.selectPvStudentRecordListByStuId(userId);
    }


    /**
     * 默认全部零分
     */
    private List<Integer> createScore(String fileName){
        JSONArray objects = JSONUtil.parseArray(ResourceUtil.readUtf8Str("json/" + fileName + ".json"));
        List<Integer> list = ListUtil.list(true);
        for (int i = 0; i < objects.size()-1; i++) {
            list.add(0);
        }
        return list;
    }

}
